import { Modal } from "antd";
import React, { useState, forwardRef, Ref, useImperativeHandle } from "react";
import ReactMarkdown from "react-markdown";
import { getPostById } from "@/api/modules/post";
import { PostDetail } from "@/api/interface/post";

interface Props {
	ref: React.Ref<any>;
}

export type ViewPostDetailModalMethods = {
	showModal: (postId: string) => void; // 定义子组件的方法
};

type ViewPostDetailModalRef = Ref<ViewPostDetailModalMethods>;

const ViewPostDetailModal = forwardRef((props: Props, ref: ViewPostDetailModalRef) => {
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [post, setPost] = useState<PostDetail>();
	const [markdown, setMarkdown] = useState("");
	const showModal = async (postId: string) => {
		const { code, data } = await getPostById(postId);
		if (code === 200) {
			setPost(data);
			setMarkdown(data?.content || "");
		}
		setIsModalOpen(true);
	};

	const handleOk = () => {
		setIsModalOpen(false);
	};

	const handleCancel = () => {
		setIsModalOpen(false);
	};

	useImperativeHandle(ref, () => ({
		// 使用useImperativeHandle来暴露子组件的方法
		showModal
	}));

	return (
		<div>
			<Modal width="80%" title={post?.postName} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
				<ReactMarkdown>{markdown}</ReactMarkdown>
			</Modal>
		</div>
	);
});

ViewPostDetailModal.displayName = ViewPostDetailModal.name;
export default ViewPostDetailModal;
